/* eslint no-underscore-dangle: 0 */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Button, Table, Pagination, Icon, Message, Grid, Dialog, Checkbox } from '@alifd/next';
import IceContainer from '@icedesign/container';
import axios from '../../../../instances/request';
import FoundationSymbol from '@icedesign/foundation-symbol';
import GroupControlFormDialog from './GroupControlFormDialog';
import {browsePrivilegesConfig} from "../../../../conf/privilegesConfig";
import {
  FormBinderWrapper as IceFormBinderWrapper,
  FormBinder as IceFormBinder,
  FormError as IceFormError,
} from '@icedesign/form-binder';

const { Row, Col } = Grid;

export default class GroupOperationTable extends Component {
  static displayName = 'GroupOperationTable';

  static propTypes = {
    limit: PropTypes.number,
  };

  static defaultProps = {
    limit: 8
  };

  constructor(props) {
    super(props);
    this.state = {
      tableData: {
        totalCount: 0,
        pageSize: this.props.limit,
        currentPage: 1,
        list: [],
        __loading: true,
      },
    };
  }

  async addOrUpdateEquipment({ id, groupname, description }) {
    let url = id == null || id === undefined ? '/superuser/group/add' : '/superuser/group/update';
    let res = await axios.post(url,{
      id,
      groupname,
      description,
    }).catch((err) => {
      Message.error(`添加或更新部门接口${err}`);
      return Promise.reject(err);
    });
    console.log("添加或更新部门接口",res);

    let { code, msg } = res.data;
    switch (code) {
      case 0:
        await this.fetchData({ page: this.state.tableData.currentPage });
        break;
      default:
        Message.error(`添加或更新部门接口code${code}`);
        return;
    }
  }

  async deleteEquipment({ id }) {
    let res = await axios.post('/superuser/group/delete', {
      id,
    }).catch((err) => {
      Message.error(`删除部门接口${err}`);
      return Promise.reject((err));
    });
    console.log("删除部门接口",res);

    let { code, msg } = res.data;
    switch (code) {
      case 0:
        await this.fetchData({ page: this.state.tableData.currentPage });
        break;
      default:
        Message.error(`删除部门接口code${code}`);
        return;
    }
  }

  async fetchData ({ page }) {
    const tableData = this.state.tableData;
    tableData.__loading = true;

    this.setState({ tableData: tableData }, async function() {
      let res = await axios.post('/superuser/group/list', {
        limit: this.props.limit,
        page: page,
      }).catch((err) => {
        Message.error(`部门管理列表接口${err}`);
        return Promise.reject(err);
      });

      console.log("部门管理列表接口", res);

      let { code, msg } = res.data;
      switch (code) {
        case 0:
          console.log(this.state.tableData);
          let { groupList, totalCount, count } = msg;
          const tableData = this.state.tableData;
          tableData.list = groupList;
          tableData.totalCount = totalCount;
          tableData.__loading = false;
          this.setState({
            tableData
          });
          break;
        default:
          Message.error(`部门管理列表接口code${code}`);
          return;
      }
    });
  };

  hookGroupControlFormDialog(value) {
    value = value || {};
    GroupControlFormDialog.show({
      value: value,
      onOk: (value) => {
        // 添加数据
        return this.addOrUpdateEquipment({
          id: value.id,
          description: value.description,
          groupname: value.groupname,
        }).then(() => {
          GroupControlFormDialog.hide();
          Message.success(value.id ? "修改部门成功" : "添加部门成功");
        });
      },
      onClose: () => {
        GroupControlFormDialog.hide();
      },
      onCancel: () => {
        GroupControlFormDialog.hide();
      },
    });
  }

  editItem = (record, e) => {
    e.preventDefault();
    this.hookGroupControlFormDialog(record);
  };

  deleteItem = (record, e) => {
    e.preventDefault();

    let dialog = Dialog.confirm({
      title: '删除确认',
      content: '您确认删除这一条目吗？',
      onOk: () => {
        return this.deleteEquipment({ id: record.id }).then(() => {
          dialog.hide();
          Message.success("删除成功");
        });
      },
      onCancel: () => {
        dialog.hide();
      },
      onClose: () => {
        dialog.hide();
      }
    });
  };

  setBrowsePrivilege(user) {
    this.setState({
      browsePrivileges: user.browsePrivileges || {},
    }, () => {
      let { id } = user;
      let dialog = Dialog.show({
        isFullScreen: true,
        shouldUpdatePosition: true,
        title: '设置用户浏览权限',
        content: (
          <IceFormBinderWrapper
            // todo : 这里value={} 可以刷新组件的显示
            value={this.state.browsePrivileges}
            // todo: 这里onChange里面setState，无法刷新组件的显示
            // todo: 因为这个Dialog.show函数在父组件外面创建了这个Dialog组件（直接往Dom里面插入），所以无法根据正常的父组件的state变化而变化
            // todo: 解决方案：利用DialogDecorator新建一个Dialog类，在那个类里面进行操作
            // onChange={this.onBrowsePrivilegeChange.bind(this)}
          >
            <div style={{ padding: '0px 40px' }}>
              {/*// todo: 想要用这个全选，就必须创建一个真正的React类 */}
              {/*<div style={styles.formItem}>*/}
              {/*<Checkbox label='全选' onChange={this.selectAllBrowse.bind(this)}/>*/}
              {/*</div>*/}
              {
                browsePrivilegesConfig.map((ele, idx) => {
                  return (
                    <div key={idx} style={styles.formItem}>
                      <IceFormBinder
                        name={ele.enName}
                      >
                        <Checkbox
                          label={ele.cnName}
                          defaultChecked={this.state.browsePrivileges[ele.enName]}
                        />
                      </IceFormBinder>
                    </div>
                  )
                })
              }
            </div>
          </IceFormBinderWrapper>
        ),
        onOk: () => {
          return axios
            .post('/superuser/group/privilege/set', {
              id,
              browsePrivileges: this.state.browsePrivileges
            }).then((res) => {
              let { code, msg } = res.data;
              if( code !== 0 ) {
                throw new Error(`code为${code}`);
              }
              Message.success('设置部门权限成功');
              this.fetchData({
                page: this.state.tableData.currentPage
              }).then(() => {
                dialog.hide();
              });
            });
        },
        onCancel: () => {
          dialog.hide();
        }
      });
    });
  }

  renderBrowsePrivilege = (value, index, record) => {
    let browsePrivileges = record.browsePrivileges || {};
    return (
      <div style={{ height: '40px', lineHeight: '40px', overflowY: 'auto' }}>
        <div style={{ lineHeight: '20px', display:'inline-block', verticalAlign: 'middle' }}>
          {
            Object.keys(browsePrivileges).filter((key, idx) => {
              return !!browsePrivileges[key];
            }).map((key, idx) => {
              let cnName = '';
              browsePrivilegesConfig.forEach((e, i) => {
                if(e.enName === key) {
                  cnName = e.cnName;
                }
              });
              return <div>{cnName}</div>;
            })
          }
        </div>
      </div>
    )
  };

  renderOperations = (value, index, record) => {
    return (
      <div>
        <div className="operation-table-operation">
        <span
          style={{ color: 'rgba(49, 128, 253, 0.65)', cursor: 'pointer' }}
          onClick={this.editItem.bind(this, record)}
        >
            编辑
        </span>
          <span style={styles.separator}/>
          <span
            style={{ color: 'rgba(49, 128, 253, 0.65)', cursor: 'pointer' }}
            onClick={ this.deleteItem.bind(this, record) }
          >
            删除
        </span>
        </div>
        <div style={{ marginTop: '5px' }}>
          <span
            style={{ color: 'rgba(49, 128, 253, 0.65)', cursor: 'pointer' }}
            onClick={ this.setBrowsePrivilege.bind(this, record) }
          >
            设置部门权限
          </span>
        </div>
      </div>
    );
  };

  changePage = (currentPage) => {
    const tableData = this.state.tableData;
    tableData.currentPage = currentPage;
    this.setState({
      tableData
    },() => {
      this.fetchData({ page: currentPage });
    });
  };

  addEquipment = () => {
    this.hookGroupControlFormDialog();
  };

  async componentDidMount() {
    await this.fetchData({
      page: 1
    });
  }

  render() {
    const tableData = this.state.tableData;

    return (
      <div className="operation-table">
        <IceContainer style={styles.cardContainer}>
          <Row>
            <Col>
              <div style={{ height: '60px', background: '#EAEBEF' }}>
                <div style={
                  {
                    float: 'left',
                    fontSize: '20px',
                    fontWeight: 'bold',
                    height: '60px',
                    lineHeight: '60px',
                    paddingLeft: '30px',
                  }
                }>
                  <FoundationSymbol type='fans' style={{ display: 'inline', verticalAlign: 'middle' }}/>
                  <span>&nbsp;部门管理</span>
                </div>
                <div
                  style={
                    {
                      height: '60px',
                      lineHeight: '60px',
                      float: 'right',
                      marginRight: '20px',
                    }
                  }
                >
                  <Button style={styles.addButton} type='primary' onClick={this.addEquipment}>添加部门</Button>
                </div>
              </div>
            </Col>
          </Row>
          <Table
            isZebra={true}
            dataSource={tableData.list}
            loading={tableData.__loading}
            className="basic-table"
            hasBorder={false}
            primaryKey="key"
            style={{ padding: '0 20px', margin: '10px 0 0 0' }}
          >
            <Table.Column
              title="部门名称"
              dataIndex='groupname'
              width={320}
              align='left'
            />
            <Table.Column
              title="浏览权限"
              width={300}
              align='left'
              cell={this.renderBrowsePrivilege}
            />
            <Table.Column
              title="部门描述"
              dataIndex="description"
              width={320}
              align='left'
            />
            <Table.Column
              title="部门人员"
              align='center'
              dataIndex="teamMembers"
              width={320}
              cell={(value, index, row) => {
                return (
                  <div style={{ height: '35px', overflowY: 'auto' }}>
                    <table style={{ border: 'none', background: 'transparent' }}>
                      <tr style={{ border: 'none' }}>
                        <th style={{ border: 'none' }}></th>
                        <th style={{ border: 'none' }}></th>
                        <th style={{ border: 'none' }}></th>
                        <th style={{ border: 'none' }}></th>
                      </tr>
                      <tbody>
                      {
                        row.teamMembers.map((user, idx) => {
                          if(idx % 4 === 0) {
                            return <tr key={idx} style={{ textAlign: 'center', border: 'none', padding: '4px 0' }}>
                              <td style={{ border: 'none' }}>&nbsp;{row.teamMembers[idx]}&nbsp;</td>
                              {
                                row.teamMembers[idx + 1] &&
                                <td style={{ border: 'none' }}>&nbsp;{row.teamMembers[idx + 1]}&nbsp;</td>
                              }
                              {
                                row.teamMembers[idx + 2] &&
                                <td style={{ border: 'none' }}>&nbsp;{row.teamMembers[idx + 2]}&nbsp;</td>
                              }
                              {
                                row.teamMembers[idx + 3] &&
                                <td style={{ border: 'none' }}>&nbsp;{row.teamMembers[idx + 3]}&nbsp;</td>
                              }
                            </tr>
                          }
                        })
                      }
                      </tbody>
                    </table>
                  </div>
                )
              }}
            />
            <Table.Column
              title="操作"
              width={150}
              cell={this.renderOperations}
            />
          </Table>
          <div style={styles.paginationContainer}>
            <Pagination
              current={tableData.currentPage}
              pageSize={this.props.limit}
              total={tableData.totalCount}
              onChange={this.changePage}
            />
          </div>
        </IceContainer>
      </div>
    );
  }
}

const styles = {
  cardContainer: {
    padding: '0 0 20px 0',
  },
  titleCol: {
    display: 'flex',
    flexDirection: 'row',
  },
  titleText: {
    marginLeft: '10px',
    lineHeight: '20px',
  },
  operBtn: {
    display: 'inline-block',
    width: '24px',
    height: '24px',
    borderRadius: '999px',
    color: '#929292',
    background: '#f2f2f2',
    textAlign: 'center',
    cursor: 'pointer',
    lineHeight: '24px',
    marginRight: '6px',
  },
  paginationContainer: {
    textAlign: 'right',
    paddingTop: '26px',
    paddingRight: '20px',
  },
  operationTableTitle: {
    fontSize: '18px',
    fontWeight: 'bold',
    fontColor: 'black',
    height: '32px',
    lineHeight: '30px',
    margin: '20px 0 20px 20px',
    paddingLeft: '12px',
    borderLeft: '4px solid rgb(102, 102, 102)',
  },
  addButton: {
  },
  separator: {
    margin: '0 4px',
    display: 'inline-block',
    height: '12px',
    width: '1px',
    verticalAlign: 'middle',
    background: '#e8e8e8',
  },
  formItem: {
    display: 'flex',
    alignItems: 'center',
    margin: '10px 0px 10px 15px',
  },
  formLabel: {
    minWidth: '60px',
  },
};
